var express = require("express");
var router = express.Router();
var { behaviors } = require("./behaviors");

//获取完整模拟数据
router.get("/", async function (req, res, next) {
  let result = behaviors();
  res.send({ code: 0, msg: "获取成功", data: result });
});

//获取某款饮品下的数据
router.get("/get/:id", async function (req, res, next) {
  let id = req.params.id;
  let result = behaviors();
  if (result.commodities) {
    result = result.commodities.filter((r) => r.id == id)[0];
  }
  res.send({ code: 0, msg: "获取成功", data: result });
});

//分页显示所有饮品
router.get("/list", async function (req, res, next) {
  let { page, limit } = req.query;
  console.log(page,limit);
  let result = behaviors();
  let list = [];
  //将所有饮品放入临时数组中
  if (result.commodities) {
    result.commodities.forEach(item => { 
      item.rows.forEach(e => { 
        list.push(e);
      })
    })
  }

  //临时数据的模拟分页处理
  let pages = list.splice((page - 1) * limit, limit);

  //如果还有数据，传输数据。否则传输没有更多数据
  if (pages.length > 0) {
    res.send({ code: 0, msg: "获取成功", data: pages });
  }
  else { 
    res.send({ code: -1, msg: "获取失败，没有更多的数据", data: null });
  }  
});

module.exports = router;